package com.gongpingjialoan.activity.car;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.Toast;

import com.gongpingjialoan.R;
import com.gongpingjialoan.activity.fb.MyPushIntentService;
import com.gongpingjialoan.activity.main.BaseActivity;
import com.gongpingjialoan.activity.main.LoginActivity;
import com.gongpingjialoan.activity.main.MainActivity;
import com.gongpingjialoan.api.Piont;
import com.gongpingjialoan.bean.Monitor;
import com.gongpingjialoan.global.GPJApplication;
import com.gongpingjialoan.manage.PointRecordManage;
import com.gongpingjialoan.utility.SharedPreferencesUtil;
import com.gongpingjialoan.utility.StepMonitor;
import com.gongpingjialoan.utility.StepRecord;
import com.handmark.pulltorefresh.library.smarttablayout.SmartTabLayout;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

/***
 * 车源详情 hqh
 *
 * @author Administrator
 */
public class CarBuyDetailActivity extends BaseActivity implements OnClickListener {

    public String mProductId = "", mTitle = "";

    public String fromType = "";

    public String from = "buycar", filter_city = "", filter_province = "";

    private ImageView reportImageView, rightImg;


    private String[] titles = {"二手车详情", "同系列好车", "同价位好车"};

    private ViewPager viewPager;

    private SmartTabLayout tabLayout;

    private String car_url, mYear, mModelName, mPrice, mThumbnailUrl;

    private SecondDetailFragment secondDetailFragment;

    private CityWideFragment cityWideFragment;

    private SamePriceCarFragment samePriceCarFragment;

    public boolean getDetailSuccess;

    private View closeView, zhapainView;

    private static final int LOGINING = 0X0392;


    @Override
    public void initTitleBar() {
        View backV = findViewById(R.id.title_back);
        if (backV != null) {
            backV.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View arg0) {
                    onBackPressed();
                }
            });
        }
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isSendData = true;
        action = "detail";
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        setContentView(R.layout.activity_car_buy_detail);
        setTitle("车源详情");
        rightImg = (ImageView) findViewById(R.id.right_img);
        rightImg.setBackgroundResource(R.drawable.share);
        rightImg.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                PointRecordManage.getInstance().addPoint(mySelf, Piont.SourceShare);
                StepMonitor.getInstance().addMonitor(new Monitor("click", "detail_share", System.currentTimeMillis(), 1f));
                share();
            }
        });
        reportImageView = (ImageView) findViewById(R.id.right_fenxiang);
        reportImageView.setImageResource(R.drawable.jubao);
        reportImageView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                PointRecordManage.getInstance().addPoint(mySelf, Piont.SourceReportClick);
                if (GPJApplication.getInstance().isLogin()) {
                    Intent intent = new Intent(CarBuyDetailActivity.this, ReportActivity.class);
                    intent.putExtra("promo_car_id", mProductId);
                    intent.putExtra("fromBuycar", true);
                    startActivity(intent);
                } else {
                    Intent intent = new Intent(CarBuyDetailActivity.this, LoginActivity.class);
                    intent.putExtra("isRefreshDiscountCar", false);
                    startActivityForResult(intent, LOGINING);
                }
            }
        });
        String source = "", job_id = "";
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            mProductId = bundle.getString("typevalue");
            fromType = bundle.getString("type", "");
            from = bundle.getString("from", "");
            filter_city = bundle.getString("city", "");
            filter_province = bundle.getString("province", "");
            source = bundle.getString("source", "");
            job_id = bundle.getString("job_id", "");
        }
        //activity被回收执行
        if (savedInstanceState != null) {
            secondDetailFragment = (SecondDetailFragment) getSupportFragmentManager().findFragmentByTag("android:switcher:" + R.id.view_pager + ":0");
            samePriceCarFragment = (SamePriceCarFragment) getSupportFragmentManager().findFragmentByTag("android:switcher:" + R.id.view_pager + ":2");
            cityWideFragment = (CityWideFragment) getSupportFragmentManager().findFragmentByTag("android:switcher:" + R.id.view_pager + ":1");
        } else {
            if (MyPushIntentService.CAR_DETAIL.equals(fromType) || MyPushIntentService.PRICECHANGE.equals(fromType)) {
                from = "push";
                StepRecord.recordStep(this, "pushnotification", "{type:" + fromType + ",typevalue:" + mProductId + ",source:" + source + ",job_id:" + job_id + "}");
            }
            secondDetailFragment = new SecondDetailFragment();
            cityWideFragment = new CityWideFragment();
            samePriceCarFragment = new SamePriceCarFragment();
        }

        closeView = findViewById(R.id.close);
        zhapainView = findViewById(R.id.zhapian);

        if ((boolean) SharedPreferencesUtil.get(this, "buycar_notification_show", true)) {
            zhapainView.setVisibility(View.VISIBLE);
        }
        closeView.setOnClickListener(this);
        secondDetailFragment.setCarId(mProductId);
        viewPager = (ViewPager) findViewById(R.id.view_pager);
        viewPager.setOffscreenPageLimit(3);
        tabLayout = (SmartTabLayout) findViewById(R.id.tableLayout);
        viewPager.setAdapter(new DetailPager(getSupportFragmentManager()));
        tabLayout.setViewPager(viewPager);
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (getDetailSuccess) {
                    if (position == 0) {
                        PointRecordManage.getInstance().addPoint(mySelf, Piont.SourceDetailTab);
                        StepMonitor.getInstance().addMonitor(new Monitor("enter", "detail", System.currentTimeMillis(), roll_pages));
                        rightImg.setVisibility(View.VISIBLE);
                        reportImageView.setVisibility(View.VISIBLE);
                    } else {
                        rightImg.setVisibility(View.GONE);
                        reportImageView.setVisibility(View.GONE);
                    }

                    if (position == 1) {
                        PointRecordManage.getInstance().addPoint(mySelf, Piont.SourceSameModelTab);
                        StepMonitor.getInstance().addMonitor(new Monitor("enter", "detail_sameModelCar", System.currentTimeMillis(), roll_pages));
                    }

                    if (position == 2) {
                        PointRecordManage.getInstance().addPoint(mySelf, Piont.SourceSamePriceTab);
                        StepMonitor.getInstance().addMonitor(new Monitor("enter", "detail_samePriceCar", System.currentTimeMillis(), roll_pages));
                    }
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    @Override
    public void onClick(View v) {
        if (v == closeView) {
            zhapainView.setVisibility(View.GONE);
            SharedPreferencesUtil.put(this, "buycar_notification_show", false);
        }
    }

    private class DetailPager extends FragmentPagerAdapter {

        public DetailPager(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            if (position == 0) {
                return secondDetailFragment;
            } else if (position == 1) {
                return cityWideFragment;
            } else if (position == 2) {
                return samePriceCarFragment;
            }
            return null;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return titles[position];
        }

        @Override
        public int getCount() {
            return 3;
        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onBackPressed() {
        //表示从推送而来
        if (MyPushIntentService.CAR_DETAIL.equals(fromType) || MyPushIntentService.PRICECHANGE.equals(fromType)) {
            Intent intent = new Intent(this, MainActivity.class);
            startActivity(intent);
            finish();
        } else {
            super.onBackPressed();
        }
    }


    public void loadSuccess(String tilte, String car_url, String mModelName, String mYear, String mPrice, String mThumbnailUrl) {
        if (isFinishing()) return;
        this.mTitle = tilte;
        this.car_url = car_url;
        this.mModelName = mModelName;
        this.mYear = mYear;
        this.mPrice = mPrice;
        this.mThumbnailUrl = mThumbnailUrl;
        reportImageView.setVisibility(View.VISIBLE);
        rightImg.setVisibility(View.VISIBLE);
        getDetailSuccess = true;
        if (MainActivity.main != null && MainActivity.main.assessmentFragment != null && MainActivity.main.assessmentFragment.isAdded()) {
            MainActivity.main.assessmentFragment.mMainRecomendView.getBrowseCars();
        }
    }

    public void share() {
        String url = car_url;
        String title = mYear + "上牌 " + mModelName + " 二手车源";
        String content = "#公平价二手车#我在@公平价 上看到一辆二手车：" + mYear + "年上牌的 " + mModelName + " 。只要" + mPrice + "万元。" + "查看该二手车详情，请猛戳这里：" + url
                + " 公平价估值为您提供最透明的二手车价格信息！";
        UMImage image = new UMImage(CarBuyDetailActivity.this, mThumbnailUrl);
        new ShareAction(this).setDisplayList(SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE, SHARE_MEDIA.SINA, SHARE_MEDIA.QQ)
                .withTitle(title)
                .withMedia(image)
                .withText(content)
                .withTargetUrl(url)
                .setCallback(umShareListener)
                .open();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /** attention to this below ,must add this**/
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == LOGINING) {
                Intent intent = new Intent(CarBuyDetailActivity.this, ReportActivity.class);
                intent.putExtra("promo_car_id", mProductId);
                intent.putExtra("fromBuycar", true);
                startActivity(intent);
            }
        }
    }

    private UMShareListener umShareListener = new UMShareListener() {
        @Override
        public void onResult(SHARE_MEDIA platform) {

            Toast.makeText(CarBuyDetailActivity.this, "分享成功!", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            Toast.makeText(CarBuyDetailActivity.this, " 分享失败!", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
            Toast.makeText(CarBuyDetailActivity.this, "分享取消!", Toast.LENGTH_SHORT).show();
        }
    };

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refresh(Object o) {
        if ("remind".equals(o.toString())) {
            if (secondDetailFragment != null && secondDetailFragment.isAdded()) {
                secondDetailFragment.setReminding();
            }
        } else if ("delete_remind".equals(o.toString())) {
            if (secondDetailFragment != null && secondDetailFragment.isAdded()) {
                secondDetailFragment.deleteReminding();
            }
        }
    }


}
